#pragma once

#include "Common.hpp"
#include "Log.hpp"

class Buffer{
private:
    // 注意: 这里的起始地址：_buffer.data() 或者 &*_buffer.begin() 都可以
    char *Begin(){return &*_buffer.begin();}

    // 读写数据
    void ReadData(void *data, uint64_t len) {
        assert(len <= ReadableSize());
        std::copy(GetReadPos(), GetReadPos() + len, (char*)data);
        // MoveReadOffset(len);
    }
    void WriteData(const void *data, uint64_t len) {
        // 1. 确保可写空间足够 2. 拷贝数据
        if(len <= 0) return ;
        EnsureWriteSpace(len); 
        const char *d = static_cast<const char *>(data);
        std::copy(d, d + len, GetWritePos()); // 把 data 复制到 缓冲区
        // MoveWriteOffset(len);
    }

    void WriteBuffer(Buffer &buf) {
        return WriteData(buf.GetReadPos(), buf.ReadableSize());
    }

    void WriteString(const std::string &str) {
        return WriteData(str.c_str(), str.size());
    }

public:
    Buffer(uint64_t size = 1024): _reader_idx(0), _writer_idx(0){
        _buffer.resize(size);
    }

    // 获取当前读写位置地址
    char *GetWritePos() {return Begin() + _writer_idx;}
    char *GetReadPos(){return Begin() + _reader_idx;}
    
    // 将读写位置向后移动指定长度
    void MoveReadOffset(uint64_t len){
        assert(len <= ReadableSize());
        _reader_idx += len;
    }
    void MoveWriteOffset(uint64_t len){
        assert(len <= BufferHeadSize() + BufferTailSize());
        _writer_idx += len;
    }

    
    // 获取一行数据
    std::string GetLine(){
        char *pos = FindCRLF();
        if (pos == nullptr) {
            return "";
        }
        uint64_t len = pos - GetReadPos() + 1; // 包括 \n
        std::string str = ReadAsStringAndPop(len);
        return str;
    }

    // 获取缓冲区末尾空闲空间大小 -- 写偏移之后的空闲空间    
    uint64_t BufferTailSize() {return _buffer.size() - _writer_idx;}
    // 获取缓冲区起始空闲空间大小 -- 读偏移之前的空闲空间
    uint64_t BufferHeadSize(){return _reader_idx;}

    // 获取可读数据大小
    uint64_t ReadableSize() {return _writer_idx - _reader_idx;}

    
    // 确保可写空间足够 (移动 / 扩容)
    void EnsureWriteSpace(uint64_t len) {
        // 1. 末尾空闲空间大小足够, 直接返回
        if(BufferTailSize() >= len) return;
        // 2. 先移动读偏移
        if (len <= BufferHeadSize() + BufferTailSize()) {
            // 3. 空闲空间足够, 数据移动到起始位置
            uint64_t readable_size = ReadableSize(); // 保存当前数据大小
            // std::memmove(_buffer.data(), _buffer.data() + _reader_idx, ReadableSize());
            std::copy(GetReadPos(), GetReadPos() + readable_size, Begin()); // 将可读数据保存到起始位置
            
            // 更新读写偏移
            _writer_idx = readable_size; 
            _reader_idx = 0;
        } else {
            // 4. 扩容
            uint64_t new_size = _buffer.size() * 2; // 避免持续扩容
            while (new_size < len) {
                new_size *= 2;
            }
            _buffer.resize(new_size);
        }
    }
    void WriteAndPush(const void *data, uint64_t len) {
        WriteData(data, len);
        MoveWriteOffset(len);
    }

    void WriteStringAndPush(const std::string &str) {
        WriteString(str);
        MoveWriteOffset(str.size());
    }

    void WriteBufferAndPush(Buffer &buf) {
        WriteBuffer(buf);
        MoveWriteOffset(buf.ReadableSize());
    }

    void ReadAndPop(void *buf, uint64_t len) {
        ReadData(buf, len);
        MoveReadOffset(len);
    }

    std::string ReadAsString(uint64_t len){
        assert(len <= ReadableSize());
        std::string str;
        str.resize(len);
        ReadData(&str[0], len);
        return str;
    }

    std::string ReadAsStringAndPop(uint64_t len){
        std::string str = ReadAsString(len);
        MoveReadOffset(len);
        return str;
    }

    char *FindCRLF(){
        char *res = (char*)std::memchr(GetReadPos(), '\n', ReadableSize());
        return res;
    }

    std::string GetLineAndPop(){
        std::string str = GetLine();
        MoveReadOffset(str.size());
        return str;
    }

    // 9. 清空缓冲区   
    void clear(){
        _buffer.clear();
        _reader_idx = 0;
        _writer_idx = 0;
    }

private:
    std::vector<char> _buffer; // 使用 vector 进行内存空间管理
    // 位置, 是一个相对偏移量, 而不是绝对地址
    uint64_t _reader_idx;  // 相对读偏移
    uint64_t _writer_idx; // 相对写偏移
};